package com.sanpu.kxe.business.trade.view;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseTitleActivity;
import com.sanpu.kxe.business.trade.adapter.AllClassifyAdapter;
import com.sanpu.kxe.business.trade.adapter.TransactionAdapter;
import com.sanpu.kxe.business.trade.bean.BillTypeOutput;
import com.sanpu.kxe.business.trade.bean.TransactionOutput;
import com.sanpu.kxe.business.trade.contract.TransactionContract;
import com.sanpu.kxe.business.trade.presenter.TransactionPresenter;
import com.sanpu.kxe.business.trade.provider.TradeOpenProvider;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.utils.DateCheckPopListener;
import com.sanpu.kxe.common.view.NoScrollGridView;
import com.sanpu.kxe.jump.eventbus.FilterEvent;
import com.sanpu.kxe.module.roundview.RoundTextView;
import com.sanpu.kxe.module.wheel.interfaces.IWheelDataChangeCallback;
import com.sanpu.kxe.module.widget.VerticalSwipeRefreshLayout;
import com.sanpu.kxe.utils.ToastUtil;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Description：账单
 * Created by 薛勇军 on 2018/8/6.
 */
@Route(path = "/trade/Transaction")
public class TransactionActivity extends BaseTitleActivity implements TransactionContract.View {

    @Bind(R.id.recyclerview)
    RecyclerView vRecyclerview;
    @Bind(R.id.swipeRefreshLayout)
    VerticalSwipeRefreshLayout vSwipeRefreshLayout;

    @Bind(R.id.allClassify)
    TextView allClassify;
    @Bind(R.id.allArrowIv)
    ImageView allArrowIv;

    @Bind(R.id.allClassifyView)
    View allClassifyView;
    @Bind(R.id.emptyView)
    View emptyView;

    private LinearLayout allClassifyLl;

    private RoundTextView startDateRtv, endDateRtv;

    private EditText startMoneyEt, endMoneyEt;

    private AllClassifyAdapter mClassifyAdapter;

    private TransactionAdapter mAdapter;

    private int nowPage = 0;

    private FilterEvent mFilterEvent;

    private Animation loadInAnimation, loadOutAnimation;

    private DateCheckPopListener vCheckPopListener;

    private boolean isSelectAll = false;

    private TransactionContract.Presenter mPresenter;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_transaction;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setTitle("账单");
//        commonTitle.showRightImageView(R.drawable.ic_trans);

        allClassifyLl = ButterKnife.findById(allClassifyView, R.id.allClassifyLl);
        ButterKnife.findById(allClassifyView, R.id.moneyLl).setVisibility(View.VISIBLE);
        startMoneyEt = ButterKnife.findById(allClassifyView, R.id.startMoney);
        endMoneyEt = ButterKnife.findById(allClassifyView, R.id.endMoney);
        NoScrollGridView allClassifyGv = ButterKnife.findById(allClassifyView, R.id.allClassifyGv);
        startDateRtv = ButterKnife.findById(allClassifyView, R.id.startDateRtv);
        endDateRtv = ButterKnife.findById(allClassifyView, R.id.endDateRtv);
        mClassifyAdapter = new AllClassifyAdapter(mContext);
        allClassifyGv.setAdapter(mClassifyAdapter);
        allClassifyGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mClassifyAdapter.setNotifyData(position);
                BillTypeOutput currentBillType = ((AllClassifyAdapter)parent.getAdapter()).getItem(position);
                if (currentBillType != null && !TextUtils.isEmpty(currentBillType.getName())) {
                    if (mFilterEvent == null)
                        mFilterEvent = new FilterEvent();
                    mFilterEvent.setTransactionType(currentBillType.getType());
                    EventBus.getDefault().post(mFilterEvent);
                }
            }
        });

        ButterKnife.findById(allClassifyView, R.id.comfirmRtv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isRefresh = false;
                String startMoney= startMoneyEt.getText().toString();
                String endMoney= endMoneyEt.getText().toString();
                if (!TextUtils.isEmpty(endMoney)) {
                    BigDecimal moneyEnd = new BigDecimal(endMoney);
                    BigDecimal moneyStart = new BigDecimal(TextUtils.isEmpty(startMoney)?"0":startMoney);
                    if (moneyStart.compareTo(moneyEnd) == 1) {
                        ToastUtil.showTextViewPrompt("最低金额不能大于最高金额");
                    } else {
                        isRefresh = true;
                    }
                } else {
                    isRefresh = true;
                }
                if (isRefresh) {
                    if (mFilterEvent == null)
                        mFilterEvent = new FilterEvent();
                    mFilterEvent.setStartMoney(startMoney);
                    mFilterEvent.setEndMoney(endMoney);
                    showAllClassifyPop(true);
                    EventBus.getDefault().post(mFilterEvent);
                }
            }
        });

        vRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mAdapter = new TransactionAdapter(mContext);
        vRecyclerview.setAdapter(mAdapter);
        mAdapter.disableLoadMoreIfNotFullPage(vRecyclerview);
        mAdapter.setPreLoadNumber(2);

        final StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(mAdapter);
        vRecyclerview.addItemDecoration(headersDecor);
        mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                headersDecor.invalidateHeaders();
            }
        });

        mPresenter = new TransactionPresenter(this);
        mPresenter.getBillList(nowPage, mFilterEvent);
        mPresenter.getBillType();
    }

    @Override
    protected void setListener() {
        super.setListener();
        vSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                nowPage = 0;
                mPresenter.getBillList(nowPage, mFilterEvent);
                mAdapter.setEnableLoadMore(true);
            }
        });
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mPresenter.getBillList(nowPage, mFilterEvent);
            }
        }, vRecyclerview);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TransactionOutput transactionOutput = ((TransactionAdapter)adapter).getItem(position);
                if (transactionOutput != null) {
                    TradeOpenProvider.getInstance().openTransactionDetailsActivity(mContext, transactionOutput);
                }
            }
        });
        emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nowPage = 0;
                mPresenter.getBillList(nowPage, mFilterEvent);
                mAdapter.setEnableLoadMore(true);
            }
        });
        ButterKnife.findById(allClassifyView, R.id.emptyView).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isRespondEvent())
                    showAllClassifyPop(true);
                return true;
            }
        });
        allClassifyView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        startMoneyEt.addTextChangedListener(mPresenter.getTextWatcher(startMoneyEt));
        endMoneyEt.addTextChangedListener(mPresenter.getTextWatcher(endMoneyEt));
        startDateRtv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (vCheckPopListener == null) {
                    vCheckPopListener = new DateCheckPopListener(TransactionActivity.this);
                }
                vCheckPopListener.handleRegionCheck(v, startDateRtv, true, new IWheelDataChangeCallback() {
                    @Override
                    public void wheelDataChangeCallback(String wheelData) {
                        if (!TextUtils.isEmpty(wheelData)) {
                            startDateRtv.setText(wheelData);
                        }
                        if (mFilterEvent == null)
                            mFilterEvent = new FilterEvent();
                        mFilterEvent.setStartTime(wheelData);
                    }
                });
            }
        });
        endDateRtv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (vCheckPopListener == null) {
                    vCheckPopListener = new DateCheckPopListener(TransactionActivity.this);
                }
                vCheckPopListener.handleRegionCheck(v, endDateRtv, true, new IWheelDataChangeCallback() {
                    @Override
                    public void wheelDataChangeCallback(String wheelData) {
                        if (!TextUtils.isEmpty(wheelData)) {
                            endDateRtv.setText(wheelData);
                        }
                        if (mFilterEvent == null)
                            mFilterEvent = new FilterEvent();
                        mFilterEvent.setEndTime(wheelData);
                    }
                });
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefresh(FilterEvent event) {
        if (event != null) {
            mFilterEvent = event;
            mAdapter.setNewData(new ArrayList<TransactionOutput>());
            nowPage = 0;
            mPresenter.getBillList(nowPage, mFilterEvent);
        }
    }

    @OnClick({R.id.allClassifyLayout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.allClassifyLayout:
                showAllClassifyPop(isSelectAll);
                break;
            default:
                break;
        }
    }

    @Override
    public void showTransactionListView(List<TransactionOutput> outputs, boolean isFirst) {
        if (outputs != null && outputs.size()>0) {
            vSwipeRefreshLayout.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);
            if (isFirst) {
                mAdapter.setNewData(outputs);
            } else {
                mAdapter.addData(outputs);
            }
            nowPage++;
        } else if (isFirst){
            vSwipeRefreshLayout.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void showLoadMore(String loadMore) {
        if (vSwipeRefreshLayout.isRefreshing()) {
            vSwipeRefreshLayout.setRefreshing(false);
        }
        switch (loadMore) {
            case CommonConfig.LOADMORECOMPLETE:
                mAdapter.loadMoreComplete();
                break;
            case CommonConfig.LOADMOREEND:
                mAdapter.loadMoreEnd();
                break;
            case CommonConfig.LOADMOREFAIL:
                mAdapter.loadMoreFail();
                break;
        }
    }

    @Override
    public void showBillTypeView(List<BillTypeOutput> billTypeOutputs) {
        BillTypeOutput retDatBean = new BillTypeOutput();
        retDatBean.setName("全部分类");
        retDatBean.setType("");
        if (billTypeOutputs == null)
            billTypeOutputs = new ArrayList<>();
        billTypeOutputs.add(0, retDatBean);
        mClassifyAdapter.setNotifyData(billTypeOutputs);
    }

    /**
     * 显示全部分类pop
     */
    private void showAllClassifyPop(boolean selectAll) {
        if (selectAll) {
            isSelectAll = false;
            allClassify.setTextColor(ContextCompat.getColor(mContext, R.color.c_909090));
            allArrowIv.setImageResource(R.drawable.ic_bottom_arrow);
            loadOutAnimation = AnimationUtils.loadAnimation(mContext,
                    R.anim.push_top_out);
            loadOutAnimation.setFillAfter(true);
            allClassifyLl.startAnimation(loadOutAnimation);
            loadOutAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    allClassifyView.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        } else {
            isSelectAll = true;
            allClassify.setTextColor(ContextCompat.getColor(mContext, R.color.color_base));
            allArrowIv.setImageResource(R.drawable.ic_top_arrow);
            allClassifyView.setVisibility(View.VISIBLE);
            loadInAnimation = AnimationUtils.loadAnimation(mContext,
                    R.anim.push_top_in);
            loadInAnimation.setFillAfter(true);
            allClassifyLl.startAnimation(loadInAnimation);
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return true;
    }

    @Override
    public void setPresenter(TransactionContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }
}
